import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'
import logoImg from '@/assets/logo/logo.png'

// 添加一些调试信息
console.log('初始化时的token:', getToken())

const user = {
  state: {
    token: getToken(),
    id: '',
    name: '',
    avatar: logoImg,
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      console.log('提交登录:', { username, code, uuid });
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          console.log('登录成功响应:', res);
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          // 设置logo作为默认头像
          commit('SET_AVATAR', logoImg)
          resolve()
        }).catch(error => {
          console.error('登录失败:', error);
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (!state.token) {
          console.error('获取用户信息失败: 没有token');
          reject('获取用户信息失败: 没有token');
          return;
        }
        
        console.log('获取用户信息, token:', state.token);
        getInfo().then(res => {
          console.log('获取用户信息成功:', res);
          const user = res.user
          
          // 检查用户类型，如果不是管理员则拒绝登录
          if (!user.isAdmin || user.isAdmin !== 1) {
            console.error('普通用户账号不允许登录管理平台');
            removeToken();
            return reject(new Error('普通用户账号不允许登录管理平台，请使用管理员账号'));
          }
          
          // 使用logo.png作为头像，不使用服务器返回的头像
          let avatar = logoImg;
          
          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_ID', user.userId)
          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch(error => {
          console.error('获取用户信息失败:', error);
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        try {
          // 即使API调用失败，也清除本地token信息
          logout(state.token).then(() => {
            // 处理成功情况
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            removeToken()
            resolve()
          }).catch(error => {
            console.error('登出API调用失败，但仍会清除本地token:', error);
            // 即使后端API调用失败，也清除本地token
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            removeToken()
            resolve() // 依然resolve而不是reject
          })
        } catch (e) {
          console.error('登出过程发生异常，但仍会清除本地token:', e);
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
